/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.tor.tribes.reportserver.util;

import de.tor.tribes.reportserver.PersistenceImpl;
import de.tor.tribes.types.ZebraReportAccessGrant;
import de.tor.tribes.types.ZebraReportUnit;
import java.io.StringWriter;
import java.util.Arrays;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

/**
 *
 * @author Torridity
 */
public class VelocityReportRenderer {

    private PersistenceImpl persistence;
    private VelocityEngine engine;
    private Template template;

    public VelocityReportRenderer(PersistenceImpl pPersistence, VelocityEngine pEngine) throws Exception {
        // Properties p = new Properties();
        // p.load(new FileInputStream(new File("h:/velocity.properties")));
        //  Velocity.init(p);
        persistence = pPersistence;
        engine = pEngine;
        template = engine.getTemplate("dsbericht.vm");
    }

    public String renderReport(ZebraReportAccessGrant pGrant) {
        VelocityContext context = new VelocityContext();
        ZebraReportUnit[] attUnits = pGrant.getReport().getAttackers().toArray(new ZebraReportUnit[]{});
        context.put("attackers", attUnits);
        context.put("attackerCount", attUnits.length);
        ZebraReportUnit[] defUnits = pGrant.getReport().getDefenders().toArray(new ZebraReportUnit[]{});
        context.put("defenders", defUnits);
        context.put("defenderCount", defUnits.length);

        if (pGrant.isShareAttackers()) {
            Arrays.sort(attUnits);
            context.put("attackers", attUnits);
        }
        if (pGrant.isShareAttackerLosses()) {
            ZebraReportUnit[] units = pGrant.getReport().getLostAttackers().toArray(new ZebraReportUnit[]{});
            Arrays.sort(units);
            context.put("lostAttackers", units);
        }

        if (pGrant.isShareDefenders()) {
            Arrays.sort(defUnits);
            context.put("defenders", defUnits);
        } else {
            ZebraReportUnit[] units = pGrant.getReport().getDefenders().toArray(new ZebraReportUnit[]{});
            context.put("defenderCount", units.length);
        }

        if (pGrant.isShareDefenderLosses()) {
            ZebraReportUnit[] units = pGrant.getReport().getLostDefenders().toArray(new ZebraReportUnit[]{});
            Arrays.sort(units);
            context.put("lostDefenders", units);
        }

        context.put("units", persistence.getUnits());
        context.put("grant", pGrant);

        StringWriter sw = new StringWriter();
        template.merge(context, sw);
        return sw.toString();
    }
}
